
//
//  UIView+Category.m
//  TestButton
//
//  Created by LQiyue on 16/4/28.
//  Copyright © 2016年 LQiyue. All rights reserved.
//

#import "UIView+Category.h"
#import <objc/runtime.h>


#define kTagBadgeView  1000
#define kTagBadgePointView  1001
#define kTagLineView 1007

@implementation UIView (Category)

static char LoadingViewKey, BlankPageViewKey;

- (void)setTwoTopCorner {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(12,12)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

- (void)setTwoTopCorner:(CGFloat)radius {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(radius,radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}
/// 设置底部两个圆角
- (void)setTwoBottomCorner:(CGFloat)radius {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(radius,radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

- (void)setTwoLeftCorner {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(12,12)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

- (void)setTwoRightCorner {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(12,12)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}
- (void)setTopLeftBottomRightCorner:(CGFloat)radius {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(radius,radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

- (void)setOneCorner:(UIRectCorner)corner radius:(CGFloat)radius {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(radius,radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

- (void)doCircleFrame {
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = self.frame.size.width/2;
    self.layer.borderWidth = 0.5;
    self.layer.borderColor = [UIColor colorWithHexString:@"0xdddddd"].CGColor;
}
- (void)doNotCircleFrame {
    self.layer.cornerRadius = 0.0;
    self.layer.borderWidth = 0.0;
}

- (void)setCornerRadius:(CGFloat)radius {
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = radius;
}

- (void)doBorderWidth:(CGFloat)width color:(UIColor *)color cornerRadius:(CGFloat)cornerRadius {
    
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = cornerRadius;
    if (width != 0) {
        self.layer.borderWidth = width;
    }
    if (color != nil) {
        self.layer.borderColor = color.CGColor;
    }
//    if (!color) {
//        self.layer.borderColor = [UIColor colorWithHexString:@"0xdddddd"].CGColor;
//    }else{
//        self.layer.borderColor = color.CGColor;
//    }
}

- (UIViewController *)findViewController
{
    for (UIView* next = self; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

- (void)addBadgePoint:(NSInteger)pointRadius withPosition:(BadgePositionType)type {
    
    if(pointRadius < 1)
        return;
    
    [self removeBadgePoint];
    
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = kTagBadgePointView;
    badgeView.layer.cornerRadius = pointRadius;
    badgeView.backgroundColor = [UIColor redColor];
    
    switch (type) {
            
        case BadgePositionTypeMiddle:
            badgeView.frame = CGRectMake(0, self.frame.size.height / 2 - pointRadius, 2 * pointRadius, 2 * pointRadius);
            break;
            
        default:
            badgeView.frame = CGRectMake(self.frame.size.width - 2 * pointRadius, 0, 2 * pointRadius, 2 * pointRadius);
            break;
    }
    
    [self addSubview:badgeView];
}

- (void)addBadgePoint:(NSInteger)pointRadius withPointPosition:(CGPoint)point {
    
    if(pointRadius < 1)
        return;
    
    [self removeBadgePoint];
    
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = kTagBadgePointView;
    badgeView.layer.cornerRadius = pointRadius;
    badgeView.backgroundColor = [UIColor colorWithHexString:@"0xf75388"];
    badgeView.frame = CGRectMake(0, 0, 2 * pointRadius, 2 * pointRadius);
    badgeView.center = point;
    [self addSubview:badgeView];
}

- (void)removeBadgePoint {
    
    for (UIView *subView in self.subviews) {
        
        if(subView.tag == kTagBadgePointView)
            [subView removeFromSuperview];
    }
}

- (void)addBadgeTip:(NSString *)badgeValue withCenterPosition:(CGPoint)center {
    if (!badgeValue || !badgeValue.length) {
        [self removeBadgeTips];
    }else{
        UIView *badgeV = [self viewWithTag:kTagBadgeView];
        if (badgeV && [badgeV isKindOfClass:[UIBadgeView class]]) {
            [(UIBadgeView *)badgeV setBadgeValue:badgeValue];
            badgeV.hidden = NO;
        }else{
            badgeV = [UIBadgeView viewWithBadgeTip:badgeValue];
            badgeV.tag = kTagBadgeView;
            [self addSubview:badgeV];
        }
        [badgeV setCenter:center];
    }
}
- (void)addBadgeTip:(NSString *)badgeValue {
    if (!badgeValue || !badgeValue.length) {
        [self removeBadgeTips];
    }else{
        UIView *badgeV = [self viewWithTag:kTagBadgeView];
        if (badgeV && [badgeV isKindOfClass:[UIBadgeView class]]) {
            [(UIBadgeView *)badgeV setBadgeValue:badgeValue];
        }else{
            badgeV = [UIBadgeView viewWithBadgeTip:badgeValue];
            badgeV.tag = kTagBadgeView;
            [self addSubview:badgeV];
        }
        CGSize badgeSize = badgeV.frame.size;
        CGSize selfSize = self.frame.size;
        CGFloat offset = 2.0;
        [badgeV setCenter:CGPointMake(selfSize.width- (offset+badgeSize.width/2),
                                      (offset +badgeSize.height/2))];
    }
}
- (void)removeBadgeTips {
    NSArray *subViews =[self subviews];
    if (subViews && [subViews count] > 0) {
        for (UIView *aView in subViews) {
            if (aView.tag == kTagBadgeView && [aView isKindOfClass:[UIBadgeView class]]) {
                aView.hidden = YES;
            }
        }
    }
}

- (CGFloat)width
{
    return self.frame.size.width;
}

- (CGFloat)height
{
    return self.frame.size.height;
}

- (void)setCenterX:(CGFloat)centerX
{
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}

- (CGFloat)centerX
{
    return self.center.x;
}

- (void)setCenterY:(CGFloat)centerY
{
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}

- (CGFloat)centerY
{
    return self.center.y;
}

- (void)setY:(CGFloat)y {
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}
- (void)setX:(CGFloat)x {
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}
- (void)setOrigin:(CGPoint)origin {
    CGRect frame = self.frame;
    frame.origin = origin;
    self.frame = frame;
}
- (void)setHeight:(CGFloat)height {
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}
- (void)setWidth:(CGFloat)width {
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}
- (void)setSize:(CGSize)size {
    CGRect frame = self.frame;
    frame.size.width = size.width;
    frame.size.height = size.height;
    self.frame = frame;
}

- (CGFloat)maxXOfFrame {
    return CGRectGetMaxX(self.frame);
}

- (void)setSubScrollsToTop:(BOOL)scrollsToTop {
    [[self subviews] enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[UIScrollView class]]) {
            [(UIScrollView *)obj setScrollEnabled:scrollsToTop];
            *stop = YES;
        }
    }];
}
- (void)colorGradientFrom:(UIColor*)color0 toColor:(UIColor*)color1 startP:(CGPoint)point0 EndP:(CGPoint)point1
{
    //渐变设置
    CAGradientLayer *gradient = [CAGradientLayer layer];
    NSArray *colors = [NSArray arrayWithObjects:(id)color0.CGColor, (id)color1.CGColor, nil];
    //设置开始和结束位置(通过开始和结束位置来控制渐变的方向)
    gradient.startPoint = point0;
    gradient.endPoint = point1;
    gradient.colors = colors;
    gradient.locations = @[@(0.0),@(1.0f)];
    gradient.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    [self.layer insertSublayer:gradient atIndex:0];
}

- (void)addGradientLayerWithColors:(NSArray *)cgColorArray {
    [self addGradientLayerWithColors:cgColorArray locations:nil startPoint:CGPointMake(0.0, 0.5) endPoint:CGPointMake(1.0, 0.5)];
}

- (void)addGradientLayerWithColors:(NSArray *)cgColorArray locations:(NSArray *)floatNumArray startPoint:(CGPoint )startPoint endPoint:(CGPoint)endPoint{
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.frame = self.bounds;
    if (cgColorArray && [cgColorArray count] > 0) {
        layer.colors = cgColorArray;
    }else{
        return;
    }
    if (floatNumArray && [floatNumArray count] == [cgColorArray count]) {
        layer.locations = floatNumArray;
    }
    layer.startPoint = startPoint;
    layer.endPoint = endPoint;
    [self.layer addSublayer:layer];
}

/**
 *  给view设置渐变色圆角边框
 *
 *  @param view            : 要添加边框的view
 *  @param cornerRadius    : 圆角大小
 *  @param lineWidth       : 线宽
 *  @param colors          : 渐变颜色数组
 *  colors : @[(__bridge id)RGB_COLOR(117, 48,227, 1).CGColor,(__bridge id)RGB_COLOR(225, 175, 204, 1).CGColor]
 *
 */
- (void)addGradientLayerWithCornerRadius:(float)cornerRadius withLineWidth:(float)lineWidth withColors:(NSArray *)colors startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {
    
    CGRect mapRect = CGRectMake(lineWidth/2, lineWidth/2, self.frame.size.width-lineWidth, self.frame.size.height-lineWidth);
    CAGradientLayer * gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    gradientLayer.colors = colors;
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = endPoint;
    gradientLayer.cornerRadius = cornerRadius;
    
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.lineWidth = lineWidth;
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:mapRect cornerRadius:cornerRadius];
    maskLayer.path = path.CGPath;
    maskLayer.fillColor = [UIColor clearColor].CGColor;
    maskLayer.strokeColor = [UIColor blueColor].CGColor;
    gradientLayer.mask = maskLayer;
    
    self.layer.cornerRadius = 21;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(1, 1);
    self.layer.shadowOpacity = 0.1;
    self.layer.shadowRadius = 3.0;
       
    
    [self.layer addSublayer:gradientLayer];
}


+ (CGRect)frameWithOutNav{
    CGRect frame = kSCREEN_BOUNDS;
    frame.size.height -= (20+44);//减去状态栏、导航栏的高度
    return frame;
}

+ (UIViewAnimationOptions)animationOptionsForCurve:(UIViewAnimationCurve)curve
{
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
            return UIViewAnimationOptionCurveEaseInOut;
            break;
        case UIViewAnimationCurveEaseIn:
            return UIViewAnimationOptionCurveEaseIn;
            break;
        case UIViewAnimationCurveEaseOut:
            return UIViewAnimationOptionCurveEaseOut;
            break;
        case UIViewAnimationCurveLinear:
            return UIViewAnimationOptionCurveLinear;
            break;
    }
    
    return kNilOptions;
}

+ (UIView *)lineViewWithPointYY:(CGFloat)pointY {
    return [self lineViewWithPointYY:pointY andColor:[UIColor colorWithHexString:@"0xc8c7cc"]];
}

+ (UIView *)lineViewWithPointYY:(CGFloat)pointY andColor:(UIColor *)color {
    return [self lineViewWithPointYY:pointY andColor:color andLeftSpace:0];
}

+ (UIView *)lineViewWithPointYY:(CGFloat)pointY andColor:(UIColor *)color andLeftSpace:(CGFloat)leftSpace{
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(leftSpace, pointY, kSCREEN_WIDTH - leftSpace, 0.5)];
    lineView.backgroundColor = color;
    return lineView;
}

+ (void)outputTreeInView:(UIView *)view withSeparatorCount:(NSInteger)count {
    NSString *outputStr = @"";
    outputStr = [outputStr stringByReplacingCharactersInRange:NSMakeRange(0, count) withString:@"-"];
    outputStr = [outputStr stringByAppendingString:view.description];
    printf("%s\n", outputStr.UTF8String);
    
    if (view.subviews.count == 0) {
        return;
    }else{
        count++;
        for (UIView *subV in view.subviews) {
            [self outputTreeInView:subV withSeparatorCount:count];
        }
    }
}

- (void)outputSubviewTree {
    [UIView outputTreeInView:self withSeparatorCount:0];
}

- (void)addLineUp:(BOOL)hasUp andDown:(BOOL)hasDown {
    [self addLineUp:hasUp andDown:hasDown andColor:[UIColor colorWithHexString:@"0xEAEAEA"] ];
}

- (void)addLineUp:(BOOL)hasUp andDown:(BOOL)hasDown andColor:(UIColor *)color {
    [self removeViewWithTag:kTagLineView];
    if (hasUp) {
        UIView *upView = [UIView lineViewWithPointYY:0 andColor:color];
        upView.tag = kTagLineView;
        [self addSubview:upView];
    }
    if (hasDown) {
        UIView *downView = [UIView lineViewWithPointYY:CGRectGetMaxY(self.bounds)-0.5 andColor:color];
        downView.tag = kTagLineView;
        [self addSubview:downView];
    }
    return [self addLineUp:hasUp andDown:hasDown andColor:color andLeftSpace:0];
}
- (void)addLineUp:(BOOL)hasUp andDown:(BOOL)hasDown andColor:(UIColor *)color andLeftSpace:(CGFloat)leftSpace{
    [self removeViewWithTag:kTagLineView];
    if (hasUp) {
        UIView *upView = [UIView lineViewWithPointYY:0 andColor:color andLeftSpace:leftSpace];
        upView.tag = kTagLineView;
        [self addSubview:upView];
    }
    if (hasDown) {
        UIView *downView = [UIView lineViewWithPointYY:CGRectGetMaxY(self.bounds)-0.5 andColor:color andLeftSpace:leftSpace];
        downView.tag = kTagLineView;
        [self addSubview:downView];
    }
}
- (void)removeViewWithTag:(NSInteger)tag{
    for (UIView *aView in [self subviews]) {
        if (aView.tag == tag) {
            [aView removeFromSuperview];
        }
    }
}

- (void)addRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:cornerRadii];
    CAShapeLayer *maskLayer = [CAShapeLayer new];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

- (CGSize)doubleSizeOfFrame{
    CGSize size = self.frame.size;
    return CGSizeMake(size.width*2, size.height*2);
}







#pragma mark -
#pragma mark - LoadingView

- (void)setLoadingView:(LoadingView *)loadingView{
    [self willChangeValueForKey:@"LoadingViewKey"];
    objc_setAssociatedObject(self, &LoadingViewKey,
                             loadingView,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"LoadingViewKey"];
}
- (LoadingView *)loadingView{
    return objc_getAssociatedObject(self, &LoadingViewKey);
}
- (void)atViewCenter
{
    for (UIView *aView in [self.blankPageContainer subviews]) {
           if ([aView isKindOfClass:[LoadBlankPageView class]] && !aView.hidden) {
               return;
           }
       }
       
       if (self.loadingView == nil) {
           //初始化LoadingView
           self.loadingView = [[LoadingView alloc] initWithFrame:self.bounds];
       }
       
    [self addSubview:self.loadingView];
//    [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.self.edges.equalTo(self);
//        make.self.top.equalTo(self).offset(-50);
//    }];
    [self.loadingView setCenter:CGPointMake(kSCREEN_WIDTH/2, kSCREEN_HEIGHT/2-kNavBarHeight)];
    [self.loadingView startAnimating];
}

- (void)beginLoading {
    
    for (UIView *aView in [self.blankPageContainer subviews]) {
        if ([aView isKindOfClass:[LoadBlankPageView class]] && !aView.hidden) {
            return;
        }
    }
    
    if (self.loadingView == nil) {
        //初始化LoadingView
        self.loadingView = [[LoadingView alloc] initWithFrame:self.bounds];
    }
    
    [self addSubview:self.loadingView];
    [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.self.edges.equalTo(self);
        make.self.top.equalTo(self).offset(-50);
    }];
    [self.loadingView startAnimating];
    
}

- (void)centerLoading {
    
    for (UIView *aView in [self.blankPageContainer subviews]) {
        if ([aView isKindOfClass:[LoadBlankPageView class]] && !aView.hidden) {
            return;
        }
    }
    
    if (self.loadingView == nil) {
        //初始化LoadingView
        self.loadingView = [[LoadingView alloc] initWithFrame:self.bounds];
    }
    
    [self addSubview:self.loadingView];
    [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.self.edges.equalTo(self);
        make.self.top.equalTo(self).offset(self.height/2 - 5);
    }];
    [self.loadingView startAnimating];
    
}

- (void)showLoadingWithTop:(CGFloat)top {
    
    for (UIView *aView in [self.blankPageContainer subviews]) {
        if ([aView isKindOfClass:[LoadBlankPageView class]] && !aView.hidden) {
            return;
        }
    }
    if (self.loadingView == nil) {
        //初始化LoadingView
        self.loadingView = [[LoadingView alloc] initWithFrame:self.bounds];
    }
    [self addSubview:self.loadingView];
    self.loadingView.activityIndicator.center = self.loadingView.center;
    [self.loadingView startAnimating];
}

- (void)endLoading{
    if (self.loadingView) {
        [self.loadingView stopAnimating];
    }
}
- (BOOL)isLoadAnimating
{
    if (self.loadingView) {
        return self.loadingView.isLoading;
    }
    return NO;
}



#pragma mark - BlankPageView
- (void)setBlankPageView:(LoadBlankPageView *)blankPageView {
    [self willChangeValueForKey:@"BlankPageViewKey"];
    objc_setAssociatedObject(self, &BlankPageViewKey,
                             blankPageView,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"BlankPageViewKey"];
}

- (LoadBlankPageView *)blankPageView {
    return objc_getAssociatedObject(self, &BlankPageViewKey);
}

- (void)configBlankPage:(LoadBlankPageType)blankPageType hasData:(BOOL)hasData hasError:(BOOL)hasError reloadButtonBlock:(void (^)(id))block {
    if (hasData) {
        if (self.blankPageView) {
            self.blankPageView.hidden = YES;
            [self.blankPageView removeFromSuperview];
        }
    } else {
        if (!self.blankPageView) {
            self.blankPageView = [[LoadBlankPageView alloc] initWithFrame:self.bounds];
            self.blankPageView.backgroundColor = [UIColor whiteColor];
        }
        self.blankPageView.hidden = NO;
        [self.blankPageContainer addSubview:self.blankPageView];
        [self.blankPageView configWithType:blankPageType hasData:hasData hasError:hasError reloadButtonBlock:block];
    }
}

- (UIView *)blankPageContainer{
    UIView *blankPageContainer = self;
    for (UIView *aView in [self subviews]) {
        if ([aView isKindOfClass:[UITableView class]]) {
            blankPageContainer = aView;
        }
    }
    return blankPageContainer;
}

@end


@interface LoadingView ()
@property (nonatomic, assign) CGFloat loopAngle, monkeyAlpha, angleStep, alphaStep;
@end


@implementation LoadingView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
        CGFloat activityHeight = 30;
        _loadingLabel = [[UILabel alloc] initWithFrame:CGRectZero];
//        [_loadingLabel setText:@"加载中..."];
        [_loadingLabel setFont:[UIFont systemFontOfSize:14.0f]];
        [_loadingLabel setTextColor:[UIColor colorWithWhite:0.641 alpha:1.000]];
        [_loadingLabel sizeToFit];
        [_loadingLabel setTextAlignment:NSTextAlignmentCenter];
        CGRect loadingRect = _loadingLabel.frame;
        loadingRect.origin.y = (self.frame.size.height-loadingRect.size.height)/2 + activityHeight/2 - 10 - 8;
        loadingRect.origin.x = (self.frame.size.width-loadingRect.size.width)/2 + activityHeight/2 - 5;
        _loadingLabel.frame = loadingRect;
        _loadingLabel.alpha = 0.0f;
        _loadingLabel.frame = CGRectMake(0, self.centerY - 10, self.width, 20);
        [self addSubview:_loadingLabel];
        
        _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityIndicator.frame = CGRectMake(self.centerX - 15, (self.frame.size.height-activityHeight)/2 - activityHeight, activityHeight, activityHeight);
        [_activityIndicator startAnimating];
        [self addSubview:_activityIndicator];
        
    }
    return self;
}

- (void)startAnimating{
    self.hidden = NO;
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    
    [self showActLoadingView];
    // [self loadingAnimation];
}

- (void)stopAnimating{
    self.hidden = YES;
    _isLoading = NO;
    [self hideActLoadingView];
}

- (void)showActLoadingView {
    ESWeak_(self);
    [UIView animateWithDuration:0.3f animations:^{
        self.alpha = 1.0f;
        weak_self.loadingLabel.alpha = 1.0f;
        weak_self.activityIndicator.alpha = 1.0f;
        [weak_self.activityIndicator startAnimating];
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)hideActLoadingView {
    ESWeak_(self)
    [UIView animateWithDuration:0.3f animations:^{
        self.alpha = 0.0f;
        weak_self.loadingLabel.alpha = 0.0f;
        weak_self.activityIndicator.alpha = 0.0f;
        [weak_self.activityIndicator stopAnimating];
    } completion:^(BOOL finished) {
        
    }];
}


// 闲置
- (void)loadingAnimation {
    static CGFloat duration = 0.25f;
    _loopAngle += _angleStep;
    if (_monkeyAlpha >= 1.0 || _monkeyAlpha <= 0.0) {
        _alphaStep = -_alphaStep;
    }
    _monkeyAlpha += _alphaStep;
    ESWeak_(self);
    [UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
        
        CGAffineTransform loopAngleTransform = CGAffineTransformMakeRotation(self->_loopAngle * (M_PI / 180.0f));
        weak_self.loopView.transform = loopAngleTransform;
        
        weak_self.loadImageView.alpha = weak_self.monkeyAlpha;
        
    } completion:^(BOOL finished) {
        if (weak_self.isLoading && [self superview] != nil) {
            [self loadingAnimation];
        }else{
            [self removeFromSuperview];
            
            self->_loopAngle = 0.0;
            (void)(self->_monkeyAlpha = 1),0;
            self->_alphaStep = ABS(self->_alphaStep);
            CGAffineTransform loopAngleTransform = CGAffineTransformMakeRotation(self->_loopAngle * (M_PI / 180.0f));
            self->_loopView.transform = loopAngleTransform;
            self->_loadImageView.alpha = self->_monkeyAlpha;
        }
    }];
}

@end

@implementation LoadBlankPageView

- (instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)configWithType:(LoadBlankPageType)blankPageType hasData:(BOOL)hasData hasError:(BOOL)hasError reloadButtonBlock:(void (^)(id))block{
    
    if (hasData) {
        [self removeFromSuperview];
        return;
    }
    self.alpha = 1.0;
    //    图片
    if (!_blankPageImageView) {
        _blankPageImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self addSubview:_blankPageImageView];
    }
    //    文字
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _tipLabel.backgroundColor = [UIColor clearColor];
        _tipLabel.numberOfLines = 0;
        _tipLabel.font = [UIFont systemFontOfSize:15];
        _tipLabel.textColor = [UIColor lightGrayColor];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_tipLabel];
    }
    
    //    布局
    if (hasError) {
        [_blankPageImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.bottom.equalTo(self.mas_centerY).offset(-25);
        }];
        
    } else {
        [_blankPageImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.bottom.equalTo(self.mas_centerY).offset(-15);
        }];
    }
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.centerX.equalTo(self);
        make.top.equalTo(self->_blankPageImageView.mas_bottom).offset(5);
        make.height.mas_equalTo(30);
    }];
    
    _reloadButtonBlock = nil;
    if (hasError) {
        // 加载失败
        if (!_reloadButton) {
            _reloadButton = [[UIButton alloc] initWithFrame:CGRectZero];
            [_reloadButton setTitle:@"重新加载" forState:UIControlStateNormal];
            _reloadButton.backgroundColor  = [UIColor whiteColor];
            [_reloadButton doBorderWidth:0.7 color:[UIColor colorWithWhite:0.741 alpha:1.000] cornerRadius:4];
            _reloadButton.adjustsImageWhenHighlighted = YES;
            _reloadButton.titleLabel.font = [UIFont systemFontOfSize:16];
            [_reloadButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [_reloadButton addTarget:self action:@selector(reloadButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:_reloadButton];
            [_reloadButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self);
                make.top.equalTo(self->_tipLabel.mas_bottom).offset(10);
                make.size.mas_equalTo(CGSizeMake(160, 40));
            }];
        }
        _reloadButton.hidden = NO;
        _reloadButtonBlock = block;
        NSString *imageNameError, *tipStrError;
        if (blankPageType == LoadBlankPageType_LoadNoNetwork) {
            
            imageNameError = @"load_network";
            tipStrError = @"网络连接异常，请检查网络设置";
        } else {
            imageNameError =  @"load_failed";
            tipStrError = @"加载失败";
        }
        [_blankPageImageView setImage:[UIImage imageNamed:imageNameError]];
        _tipLabel.text = tipStrError;
        
    } else {
        // 空白数据
        if (_reloadButton) {
            _reloadButton.hidden = YES;
        }
        NSString *imageName, *tipStr;
        switch (blankPageType) {
                
            case LoadBlankPageType_LoadFailed:
            {
                imageName = @"load_failed";
                tipStr = @"加载失败";
            }
                break;
            case LoadBlankPageType_LoadNoNetwork:
            {
                imageName = @"load_network";
                tipStr = @"网络连接异常，请检查网络设置";
            }
                break;
            case LoadBlankPageType_LoadEmptyData:
            {
                imageName = @"load_empty";
                tipStr = @"这里什么都没有！";
            }
                break;
            case LoadBlankPageType_View:
            {
                imageName = @"load_empty";
                tipStr = @"";
            }
                break;
            case LoadBlankPageType_LoadNoFollow:
            {
                imageName = @"load_empty";
                tipStr = @"暂无关注版块";
            }
                break;
            case LoadBlankPageType_LoadAlbumEmptyData:
            {
                imageName = @"load_empty";
                tipStr = @"暂无关注版块";
            }
                break;
            default:
            {
                imageName = @"load_failed";
                tipStr = @"";
            }
                break;
        }
        [_blankPageImageView setImage:[UIImage imageNamed:imageName]];
        _tipLabel.text = tipStr;
    }
}

- (void)reloadButtonClicked:(id)sender{
    self.hidden = YES;
    [self removeFromSuperview];
    ESWeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (__weakSelf.reloadButtonBlock) {
            __weakSelf.reloadButtonBlock(sender);
        }
    });
}

@end
